﻿package Modules.CommunicationsModule
{
	import Modules.MainTimeLine;
	
	import com.adobe.serialization.json.*;
	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.external.ExternalInterface;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	public class FacebookCallBacks
	{
		public static function callShareFT():void {
			
			var myMessage:String = "Farmer's Tale is not just your ordinary farming game! In Farmer's Tale, we encourage you to take part in volunteer activities, and in return, we will give you a little something to help you advance in the game.";
			var myTitle:String = "Play Farmer's Tale and help those in need!"
			
			if(ExternalInterface.available){
				ExternalInterface.call("publishToWall", myMessage, myTitle);
			}
		}
		public static function callShareFTcommon(myMessage:String, myTitle:String):void {
			
			if(ExternalInterface.available){
				ExternalInterface.call("publishToWall", myMessage, myTitle);
			}
		}
		
		// load player profile from fb, is self specifies load for current player?
		public static function loadProfile(id:String, isSelf:Boolean):void{
			//create loader for the profile
			var profileLoader:URLLoader = new URLLoader();
			var profileRequest:URLRequest = new URLRequest("http://graph.facebook.com/"+id);

			//create loader for the image
			var imageLoader:Loader = new Loader();
			var imageRequest:URLRequest = new URLRequest("http://graph.facebook.com/"+id+"/picture")

			profileLoader.load(profileRequest);
			imageLoader.load(imageRequest);
			
			//load the images and pass the loaders to the function
			//responsible for displaying the information and picture
			profileLoader.addEventListener(Event.COMPLETE, function finish(event:Event):void{displayProfile(id, profileLoader.data, imageLoader, isSelf)});
		}
		
		public static function displayProfile(id:String, profile:String, profileImage:Loader, isSelf:Boolean):void{
			//the retrieved profile is in json format, so have to decode it first
			//it has attributes id, name, first_name, last_name, gender
			var decodedProfile = JSON.decode(profile);
			var profileName;
			var profileId;

			/*if(profile == "false"){
				MainTimeLine.session.player.partyTable.removeMemberFromTable(id);
				return;
			}*/
			
			
			profileName = decodedProfile.name;
			profileId = decodedProfile.id;
			
			if(isSelf){
				MainTimeLine.session.player.playerName = profileName;
				MainTimeLine.session.player.picture = profileImage;
				//trace(profileName);
			}
			/*else{ // used for party members
				MainTimeLine.session.player.partyTable.setPartyPlayerName(profileId, profileName, profileImage);
			}*/
		}
	}
}